/**
 *  Created by zlgb on 2021-05-19 11:11:40
 *  ------------------修改记录-------------------
 *  修改人      修改日期                 修改目的
 *  zlgb        2021-05-19               创建
 **/
// 用于存储每个请求的标识和取消函数
const pending = new Map();
// 用于存储每个请求的开始时间
const timeStamp = new Map();
// 时间阀值
const timeHandler = 500;
/**
 * 添加请求
 * @param {Object} config
 */
interface IConfig {
  method:string,
  params:object,
  data:object,
  cancelToken:()=>void
  [key:string]:any
}
export const addPending = (axios:any,config:IConfig) => {
    const url = [
        config.method,
        config.url,
        JSON.stringify(config.params),
        JSON.stringify(config.data)
    ].join('&');
    config.cancelToken = config.cancelToken || new axios.CancelToken((cancel:any) => {
        if (!pending.has(url)) { // 如果 pending 中不存在当前请求，则添加进去
            pending.set(url, cancel);
            timeStamp.set(`${url}timeStamp`,Date.now());
        }
    });
};
/**
 * 移除请求
 * @param {Object} config
 */
export const removePending = (config:IConfig) => {
    const url = [
        config.method,
        config.url,
        JSON.stringify(config.params),
        JSON.stringify(config.data)
    ].join('&');
    const reqTimeStamp = timeStamp.get(`${url}timeStamp`);
    // 如果在 pending 中存在当前请求标识，需要取消当前请求，并且移除
    if (pending.has(url) && Date.now()-reqTimeStamp<timeHandler) {
        const cancel = pending.get(url);
        console.warn('存在重复请求，请求被取消');
        cancel(url);
        pending.delete(url);
    }
};
/**
 * 清空 pending 中的请求（在路由跳转时调用）
 */
export const clearPending = () => {
    for (const [url, cancel] of pending) {
        cancel(url);
    }
    pending.clear();
    timeStamp.clear();
    const end  = window.setTimeout(() => '', 1000);
    for (let i = 1; i <= end; i++) {
        clearInterval(i);
    }
};
